package jiwei.config;

import cn.hutool.core.io.FileTypeUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

//文件上传拦截器
public class FileInterceptor implements HandlerInterceptor {
    Logger log = LoggerFactory.getLogger(getClass());

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        // 判断是否为文件上传请求
        if (req instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartReq = (MultipartHttpServletRequest) req;
            Map<String, MultipartFile> files = multipartReq.getFileMap();

            for (String formKey : files.keySet()) {
                MultipartFile file = multipartReq.getFile(formKey);
                //后缀名文件类型
                String filename = file.getOriginalFilename();
                //String suffixType = FileUtil.extName(filename);
                String suffixType = StringUtils.substringAfterLast(filename, ".");
                //文件头文件类型
                String headerType = FileTypeUtil.getType(file.getInputStream());
                //文件头与文件名后缀不匹配
                if (!StringUtils.equalsIgnoreCase(suffixType, headerType)) {
                    String info = String.format("文件头与文件名后缀不匹配。文件名：%s，文件头：%s。", filename, headerType);
                    log.error(info);

                    resp.setStatus(HttpServletResponse.SC_OK);
                    resp.getWriter().write(info);
                    resp.flushBuffer();
                    return false;
                }
            }
        }

        return true;
    }
}
